package com.gy.bearhelps.home;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.weather.LocalDayWeatherForecast;
import com.amap.api.services.weather.LocalWeatherForecast;
import com.amap.api.services.weather.LocalWeatherForecastResult;
import com.amap.api.services.weather.LocalWeatherLive;
import com.amap.api.services.weather.LocalWeatherLiveResult;
import com.amap.api.services.weather.WeatherSearch;
import com.amap.api.services.weather.WeatherSearchQuery;
import com.google.gson.reflect.TypeToken;
import com.gy.bearhelps.MainActivity;
import com.gy.bearhelps.MyApplication;
import com.gy.bearhelps.R;
import com.gy.bearhelps.base.BaseBean;
import com.gy.bearhelps.base.BaseFragment;
import com.gy.bearhelps.base.WebViewActivity;
import com.gy.bearhelps.home.adapter.HomeAdapter;
import com.gy.bearhelps.home.adapter.HomePagerAdAdapter;
import com.gy.bearhelps.home.bean.HomePagerBean;
import com.gy.bearhelps.home.bean.WeatherBean;
import com.gy.bearhelps.news.bean.NewsItemBean;
import com.gy.bearhelps.setting.SettingMainActivity;
import com.gy.bearhelps.util.ActivityUtil;
import com.gy.bearhelps.util.AnimUtil;
import com.gy.bearhelps.util.ListViewItemListener;
import com.gy.bearhelps.util.LocationManagers;
import com.gy.bearhelps.util.LogUtil;
import com.gy.bearhelps.util.PingYinUtil;
import com.gy.bearhelps.util.RequestResultListener;
import com.gy.bearhelps.util.TimeUtil;
import com.gy.bearhelps.util.Urls;
import com.gy.bearhelps.view.PageIndicatorView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.RequestParams;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 高岳 on 2016/11/2.
 * Describe:首页
 */
public class HomeFragment extends BaseFragment implements LocationManagers.LocationChange,
        WeatherSearch.OnWeatherSearchListener,ListViewItemListener{

    private final int UPDATE_TIME = 5000;
    private ImageView imgRight;
    private PullToRefreshListView refreshListView;
    private View headerView;
    private TextView tvLocation,tvTemperatureNow,tvTemperature,tvWeather,tvAir,tvWind,tvLimit,tvLimetMsg;
    private ImageView imgShare,imgRefresh;
    private LinearLayout llDCSJ,llYMSJ,llNEED,llDCB;
    private View viewShare;
    private LinearLayout llShareWX,llShareWXCircle,llQQ,llQQZone,llShareSina,llShareMain,llShareTop;
    private ViewPager adViewPager;
    private PageIndicatorView indicatorView;
    private HomeAdapter adapter;
    private List<NewsItemBean> mLists,requestLists;
    private HomePagerAdAdapter pagerAdAdapter;
    private boolean isAdd = true;
    private ArrayList<String> adList,adRequest;
    private List<HomePagerBean> pagerLists;
    private AMapLocation aMapLocation;//定位位置信息
    private String strCity;
    private int pageStart = 0;
    private WeatherBean weatherBean;
    private PopupWindow sharePop;
    private MainActivity mainActivity;

    @Override
    protected View setView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fg_home,null);
        hidenTop();
        return view;
    }

    @Override
    protected void initView() {
        imgRight = (ImageView) _rootView.findViewById(R.id.fg_home_img_right);
        refreshListView = (PullToRefreshListView) _rootView.findViewById(R.id.fg_home_lisview);
        headerView = View.inflate(mContext,R.layout.view_home_header,null);
        tvLocation = (TextView) headerView.findViewById(R.id.view_home_headre_tv_location);
        tvTemperatureNow = (TextView) headerView.findViewById(R.id.view_home_headre_tv_temperature_now);
        tvTemperature = (TextView) headerView.findViewById(R.id.view_home_headre_tv_temperature);
        tvWeather = (TextView) headerView.findViewById(R.id.view_home_headre_tv_weather);
        tvAir = (TextView) headerView.findViewById(R.id.view_home_headre_tv_air);
        tvWind = (TextView) headerView.findViewById(R.id.view_home_headre_tv_wind);
        tvLimit = (TextView) headerView.findViewById(R.id.view_home_headre_tv_limt);
        tvLimetMsg = (TextView) headerView.findViewById(R.id.view_home_headre_tv_limt_msg);
        imgShare = (ImageView) headerView.findViewById(R.id.view_home_headre_img_share);
        imgRefresh = (ImageView) headerView.findViewById(R.id.view_home_headre_img_refresh);
        llDCSJ = (LinearLayout) headerView.findViewById(R.id.view_home_headre_ll_dcsj);
        llYMSJ = (LinearLayout) headerView.findViewById(R.id.view_home_headre_ll_ymsj);
        llNEED = (LinearLayout) headerView.findViewById(R.id.view_home_headre_ll_need);
        llDCB = (LinearLayout) headerView.findViewById(R.id.view_home_headre_ll_dcb);
        adViewPager = (ViewPager) headerView.findViewById(R.id.home_ad_viewpager);
        indicatorView = (PageIndicatorView) headerView.findViewById(R.id.home_ad_pagepoint);

        viewShare = View.inflate(mContext,R.layout.pop_share,null);
        llShareMain = (LinearLayout) viewShare.findViewById(R.id.share_ll_main);
        llShareTop = (LinearLayout) viewShare.findViewById(R.id.share_ll_top);
        llShareWX = (LinearLayout) viewShare.findViewById(R.id.share_ll_wechat);
        llShareWXCircle = (LinearLayout) viewShare.findViewById(R.id.share_ll_wxcircle);
        llQQ = (LinearLayout) viewShare.findViewById(R.id.share_ll_qq);
        llQQZone = (LinearLayout) viewShare.findViewById(R.id.share_ll_qqzone);
        llShareSina = (LinearLayout) viewShare.findViewById(R.id.share_ll_sina);
    }

    @Override
    protected void initData() {
        mainActivity = (MainActivity) getActivity();
        pagerLists = new ArrayList<>();
        adList = new ArrayList<String>();// 滚动广告数
        adRequest = new ArrayList<String>();// 滚动广告数
        mLists = new ArrayList<>();
        requestLists = new ArrayList<>();
        adapter = new HomeAdapter(mContext,mLists);
        pagerAdAdapter = new HomePagerAdAdapter(mContext,adList);
        refreshListView.getRefreshableView().addHeaderView(headerView);
        refreshListView.setAdapter(adapter);
        LocationManagers.getInstance().addListener(this);
    }

    @Override
    protected void setListener() {
        super.setListener();
        imgRight.setOnClickListener(this);
        imgShare.setOnClickListener(this);
        imgRefresh.setOnClickListener(this);
        llDCSJ.setOnClickListener(this);
        llYMSJ.setOnClickListener(this);
        llNEED.setOnClickListener(this);
        llDCB.setOnClickListener(this);

        llShareWX.setOnClickListener(this);
        llShareTop.setOnClickListener(this);
        llShareWXCircle.setOnClickListener(this);
        llQQ.setOnClickListener(this);
        llQQZone.setOnClickListener(this);
        llShareSina.setOnClickListener(this);

//        refreshListView.setMode(PullToRefreshBase.Mode.DISABLED);
        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageStart = 0;
                requestViewPager();
                getList();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
            }
        });
        refreshListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if(!isLoading && requestLists.size() >= Urls.PAGESIZE){
                    isLoading = true;
                    pageStart++;
                    getList();
                }
            }
        });
        refreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, WebViewActivity.class);
                intent.putExtra(WebViewActivity.TITLE,"首页");
                intent.putExtra(WebViewActivity.URL,mLists.get(position-2).pageUrl);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(getActivity());
            }
        });
    }

    @Override
    protected void fillData() {
        super.fillData();
        sharePop = new PopupWindow(viewShare, LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
        sharePop.setFocusable(true);
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        // 设置SelectPicPopupWindow弹出窗体的背景
        sharePop.setBackgroundDrawable(dw);
        if(MyApplication.aMapLocation != null){
            this.aMapLocation = MyApplication.aMapLocation;
            setLocation();
        }
        requestViewPager();
        getWeather();
        getList();
    }

    private void setViewPager() {
        indicatorView.setPropertise(adRequest.size(), 0);
        pagerAdAdapter = new HomePagerAdAdapter(mContext,adRequest);
        pagerAdAdapter.setListener(this);
        adViewPager.setAdapter(pagerAdAdapter);
//        adViewPager.setCurrentItem(0);
        adViewPager.setCurrentItem(adRequest.size() * 100);
        adViewPager.invalidate();
        if(adList.size() > 1){
            adSwitchHandler.postDelayed(adSwitchRunnable, UPDATE_TIME);
        }

        adViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                if(adRequest.size() > 1){
                    indicatorView.setCurrentPosition(arg0 % adRequest.size());
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                if (arg0 == 1) {
                    adSwitchHandler.removeCallbacks(adSwitchRunnable);
                } else {
                    adSwitchHandler.removeCallbacks(adSwitchRunnable);
                    adSwitchHandler.postDelayed(adSwitchRunnable, UPDATE_TIME);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Intent intent;
        switch (v.getId()){
            case R.id.fg_home_img_right:
                intent = new Intent(mContext, SettingMainActivity.class);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(getActivity());
                break;
            case R.id.view_home_headre_img_share:
                sharePop.showAtLocation(getActivity().getWindow().getDecorView(), Gravity.CENTER, 0, 0);
                break;
            case R.id.view_home_headre_img_refresh:
                requestViewPager();
                getList();
                break;
            case R.id.view_home_headre_ll_dcsj:
                intent = new Intent(mContext, CJSJActivity.class);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(getActivity());
                break;
            case R.id.view_home_headre_ll_ymsj:
                intent = new Intent(mContext, YMSJActivity.class);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(getActivity());
                break;
            case R.id.view_home_headre_ll_need:
                intent = new Intent(mContext, MapSearchActivity.class);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(getActivity());
                break;
            case R.id.view_home_headre_ll_dcb:
                intent = new Intent(mContext, DCBActivity.class);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(getActivity());
                break;
            case R.id.share_ll_top:
                sharePop.dismiss();
                break;
            case R.id.share_ll_wechat:
                if(ActivityUtil.isWeixinAvilible(mContext)){
                    mainActivity.shared(0);
                } else {
                    showToast("请先安装微信客户端");
                }
                break;
            case R.id.share_ll_wxcircle:
                if(ActivityUtil.isWeixinAvilible(mContext)){
                    mainActivity.shared(1);
                } else {
                    showToast("请先安装微信客户端");
                }
                break;
            case R.id.share_ll_qq:
                mainActivity.shared(2);
                break;
            case R.id.share_ll_qqzone:
                mainActivity.shared(3);
                break;
            case R.id.share_ll_sina:
                mainActivity.shared(4);
                break;
        }
    }

    /**
     * 更换广告页
     */
    private Handler adSwitchHandler = new Handler();
    /**
     * 更换广告页的runnable
     */
    private Runnable adSwitchRunnable = new Runnable() {

        @Override
        public void run() {

            if (null != adViewPager && null != adList && adList.size() > 0) {
                int nextPosition;
                int currentItem = adViewPager.getCurrentItem();
                if (isAdd) {
                    if (currentItem == adList.size() - 1) {
                        nextPosition = currentItem - 1;
                        isAdd = false;
                    } else {
                        nextPosition = ++currentItem;
                    }
                } else {
                    if (currentItem == 0) {
                        nextPosition = currentItem + 1;
                        isAdd = true;
                    } else {
                        nextPosition = --currentItem;
                    }
                }
                adViewPager.setCurrentItem(nextPosition, true);
            }

            adSwitchHandler.removeCallbacks(adSwitchRunnable);
            adSwitchHandler.postDelayed(adSwitchRunnable, UPDATE_TIME);
        }
    };

    @Override
    public void locationChange() {
        this.aMapLocation = MyApplication.aMapLocation;
        setLocation();
    }

    /** 设置位置信息*/
    public void setLocation(){
        strCity = aMapLocation.getDistrict();
        if(TextUtils.isEmpty(strCity)){
            strCity = aMapLocation.getCity();
        }
        tvLocation.setText(strCity);

        WeatherSearchQuery mquery = new WeatherSearchQuery(strCity, WeatherSearchQuery.WEATHER_TYPE_LIVE);
        WeatherSearch mweathersearch=new WeatherSearch(mContext);
        mweathersearch.setOnWeatherSearchListener(this);
        mweathersearch.setQuery(mquery);
        mweathersearch.searchWeatherAsyn(); //异步搜索

        WeatherSearchQuery mquery2 = new WeatherSearchQuery(aMapLocation.getCity(), WeatherSearchQuery.WEATHER_TYPE_FORECAST);
        WeatherSearch mweathersearch2=new WeatherSearch(mContext);
        mweathersearch2.setOnWeatherSearchListener(this);
        mweathersearch2.setQuery(mquery2);
        mweathersearch2.searchWeatherAsyn(); //异步搜索
        getWeather();

    }

    @Override
    public void onWeatherLiveSearched(LocalWeatherLiveResult weatherLiveResult, int rCode) {
        if (rCode == 1000) {
            if (weatherLiveResult != null && weatherLiveResult.getLiveResult() != null) {
                LocalWeatherLive weatherlive = weatherLiveResult.getLiveResult();
                LogUtil.e(weatherlive.getCity()+"  "+weatherlive.getWeather()+"---"+weatherlive.getTemperature()
                +"  "+weatherlive.getWindDirection()+"  "+weatherlive.getWindPower());
                tvTemperatureNow.setText(weatherlive.getTemperature());//温度
                tvWeather.setText(weatherlive.getWeather());//天气
                tvWind.setText(weatherlive.getWindDirection()+"风"+weatherlive.getWindPower()+"级");
                tvAir.setText("湿度 "+weatherlive.getHumidity()+"%");
            }else {
            }
        }else {
        }
    }

    @Override
    public void onWeatherForecastSearched(LocalWeatherForecastResult localWeatherForecastResult, int rCode) {
        if (rCode == 1000) {
            LocalWeatherForecast weatherForecast = localWeatherForecastResult.getForecastResult();
            List<LocalDayWeatherForecast> list = weatherForecast.getWeatherForecast();
            tvTemperature.setText(list.get(0).getNightTemp()+"/"+list.get(0).getDayTemp()+"℃");
        }

    }

    /** 请求轮播*/
    private void requestViewPager(){
        showLoadDialog();
        RequestParams params = new RequestParams(Urls.home_viewpage);
        getRequest(params, new RequestResultListener() {
            @Override
            public boolean onSuccess(BaseBean result) {
                finishHandler.sendEmptyMessageDelayed(0,200);
                Type type = new TypeToken<List<HomePagerBean>>(){}.getType();
                try {
                    JSONArray array = new JSONArray(result.data);
                    JSONObject obj = array.getJSONObject(0);
                    pagerLists = gson.fromJson(obj.optString("appList"),type);
                    adList.clear();
                    adRequest.clear();
                    for (HomePagerBean bean : pagerLists){
                        adList.add(bean.img);
                        adRequest.add(bean.img);
                    }
                    addImages();
                    setViewPager();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return false;
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                finishHandler.sendEmptyMessageDelayed(0,200);
            }
        });
    }

    /** 获取新闻列表*/
    private void getList(){
        RequestParams params = new RequestParams(Urls.select_list);
        params.addQueryStringParameter("pageSize",Urls.PAGESIZE+"");
        params.addQueryStringParameter("pageStart",pageStart+"");
        params.addQueryStringParameter("channelId","9");
        getRequest(params, new RequestResultListener() {
            @Override
            public boolean onSuccess(BaseBean result) {
                finishHandler.sendEmptyMessageDelayed(0,200);
                try {
                    JSONArray array = new JSONArray(result.data);
                    JSONObject obj = array.getJSONObject(0);
                    Type type = new TypeToken<List<NewsItemBean>>(){}.getType();
                    requestLists = gson.fromJson(obj.optString("list"),type);
                    if(pageStart == 0){
                        mLists.clear();
                    }
                    if(requestLists.size() > 0){
                        refreshListView.setVisibility(View.VISIBLE);
                        mLists.addAll(requestLists);
                        adapter.notifyDataSetChanged();
                    } else {
                        if(mLists.size() == 0){
//                            refreshListView.setVisibility(View.GONE);
                        } else {
                            showToast("已全部加载");
//                            refreshListView.setVisibility(View.VISIBLE);
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                finishHandler.sendEmptyMessageDelayed(0,200);
            }
        });
    }

    private void getWeather(){
        if(MyApplication.aMapLocation == null){
            return;
        }
        showLoadDialog();
        String city = MyApplication.aMapLocation.getCity();
        LogUtil.e(city);
        if(city.indexOf("市") != -1){
            city = city.substring(0,city.indexOf("市"));
            LogUtil.e(city);
        }
        city = PingYinUtil.getPingYin(city);
        LogUtil.e(city);
        RequestParams params = new RequestParams(Urls.get_weather);
        params.addQueryStringParameter("city",city+"");
        params.addQueryStringParameter("date", TimeUtil.getTime()+"");
        params.addHeader("apikey","2c07fa3be5330dfd252fdeb3d2b2187d ");
        getRequest(params, new RequestResultListener() {
            @Override
            public boolean onSuccess(BaseBean result) {
                weatherBean = gson.fromJson(result.data,WeatherBean.class);
                if("0".equals(weatherBean.status)){
                    tvLimit.setVisibility(View.VISIBLE);
                    if("不限行".equals(weatherBean.result.number)){
                        tvLimetMsg.setVisibility(View.INVISIBLE);
                    } else {
                        tvLimetMsg.setVisibility(View.VISIBLE);
                    }
                    tvLimit.setText(weatherBean.result.number);
                } else {
                    tvLimetMsg.setVisibility(View.INVISIBLE);
                    tvLimit.setVisibility(View.INVISIBLE);
                }

                return false;
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }
        });
    }

    @Override
    public void doPassActionListener(Object obj, int org1, int org2, String str) {
        Intent intent;
        switch (org1){
            case 0://轮播图
                if(pagerLists.get(org2) != null && !TextUtils.isEmpty(pagerLists.get(org2).url)
                        && !"#".equals(pagerLists.get(org2).url)){
                    intent = new Intent(mContext, WebViewActivity.class);
                    intent.putExtra(WebViewActivity.URL,pagerLists.get(org2).url);
                    intent.putExtra(WebViewActivity.TITLE,"首页");
                    startActivity(intent);
                    AnimUtil.pushLeftInAndOut(getActivity());
                }
                break;
        }
    }

    private void addImages(){
        indicatorView.setVisibility(View.VISIBLE);
        if (adList.size() == 1) {
            indicatorView.setVisibility(View.GONE);
        }else if (adList.size() == 2 || adList.size() == 3) {
            List<String> list = new ArrayList<>();
            list.addAll(adList);
            for (String str : list){
                adList.add(str);
            }
        } else {

        }

    }

    private Handler finishHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            refreshListView.onRefreshComplete();
        }
    };
}
